package com.example.admin.myapplication.domain.data.db

import com.example.admin.myapplication.domain.datasource.ForecastDataSource
import com.example.admin.myapplication.domain.model.ForecastList
import com.example.admin.myapplication.extensions.byId
import com.example.admin.myapplication.extensions.clear
import com.example.admin.myapplication.extensions.parseList
import com.example.admin.myapplication.extensions.parseOpt
import org.jetbrains.anko.db.select
import java.util.*


class ForecastDb(private val forecastDbHelper: ForecastDbHelper = ForecastDbHelper.instances,
                 private val dataMapper: DbDataMapper = DbDataMapper()) : ForecastDataSource {
    override fun requestForecastByZipCode(zipCode: Long, date: Long) = forecastDbHelper.use {
        val dailyRequest = "${DayForecastTable.CITY_ID}= ? AND ${DayForecastTable.DATE}>=?"
        val dailyForecast = select(DayForecastTable.NAME)
                .whereSimple(dailyRequest, zipCode.toString(), date.toString())
                .parseList { DayForeCast(HashMap(it)) }
        val city = select(CityForecastTable.NAME).whereSimple("${CityForecastTable.ID}=?", zipCode.toString()).parseOpt { CityForecast(HashMap(it), dailyForecast) }
        city?.let { dataMapper.convertToDomain(it) }
    }

    override fun requestDayForecast(id: Long) = forecastDbHelper.use {
        val forecast = select(DayForecastTable.NAME).byId(id)
                .parseOpt { DayForeCast(HashMap(it)) }
        forecast?.let {
            dataMapper.convertDayToDomain(it)
        }
    }

    fun saveForecast(forecast: ForecastList) = forecastDbHelper.use {
        clear(CityForecastTable.NAME)
        clear(DayForecastTable.NAME)
        with(dataMapper.convertFromDomain(forecast)) {
//            insert(CityForecastTable.NAME,*Map.to)
        }
    }
}

